// PDF.js 配置
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

// PDF相关变量
let pdfDoc = null;
let pageNum = 1;
let pageRendering = false;
let pageNumPending = null;
let scale = 1.0;
let canvas = null;
let ctx = null;

// 初始化页面
function init() {
    canvas = document.getElementById('pdfCanvas');
    ctx = canvas.getContext('2d');
    
    // 初始化事件监听
    
    // 全局函数，用于在浏览器控制台测试file参数处理逻辑
    window.testFileParam = function(filePath) {
        let pdfUrl = '/data/books/TanenbaumComputerNetworksEducationLimited2021.pdf';
        if (filePath) {
            pdfUrl = filePath;
            console.log('测试使用的文件路径:', pdfUrl);
        }
        
        // 验证文件路径是否包含有效的PDF文件名
        const fileName = pdfUrl.split('/').pop();
        if (!fileName.endsWith('.pdf')) {
            console.log('无效的PDF文件路径');
        } else {
            console.log('有效的PDF文件路径:', pdfUrl);
            console.log('文件名:', fileName);
        }
        
        return pdfUrl;
    };
    document.getElementById('prevPage').addEventListener('click', onPrevPage);
    document.getElementById('nextPage').addEventListener('click', onNextPage);
    document.getElementById('zoomIn').addEventListener('click', zoomIn);
    document.getElementById('zoomOut').addEventListener('click', zoomOut);
    document.getElementById('fullscreen').addEventListener('click', toggleFullscreen);
    document.getElementById('backBtn').addEventListener('click', () => {
        window.location.href = '/';
    });
    
    // 加载PDF
    loadPDF();
}

// 加载PDF文件
async function loadPDF() {
    // 重置所有PDF相关变量
    pdfDoc = null;
    pageNum = 1;
    pageRendering = false;
    pageNumPending = null;
    scale = 1.0;
    
    // 完全重新创建canvas元素，确保没有任何缓存状态
    const oldCanvas = document.getElementById('pdfCanvas');
    const canvasContainer = oldCanvas.parentElement;
    canvasContainer.removeChild(oldCanvas);
    
    const newCanvas = document.createElement('canvas');
    newCanvas.id = 'pdfCanvas';
    canvasContainer.appendChild(newCanvas);
    canvas = newCanvas;
    ctx = canvas.getContext('2d');
    
    const urlParams = new URLSearchParams(window.location.search);
    const fileParam = urlParams.get('file');
    console.log('URL参数 - file:', fileParam);
    
    // 处理传入的file参数
    let fileName = 'TanenbaumComputerNetworksEducationLimited2021.pdf'; // 默认文件名
    if (fileParam) {
        // 提取文件名（移除可能的路径部分）
        fileName = fileParam.split('/').pop();
    }
    
    // 验证文件名是否为PDF
    if (!fileName.toLowerCase().endsWith('.pdf')) {
        showError('无效的PDF文件路径');
        showLoading(false);
        return;
    }
    
    // 使用新的特定PDF访问路由
    let pdfUrl = `/pdf-books/${fileName}`;
    
    // 添加随机参数以避免浏览器缓存
    const cacheBuster = '?t=' + new Date().getTime();
    pdfUrl = pdfUrl + cacheBuster;
    
    showLoading(true);
    
    try {
        console.log('正在加载PDF文件:', pdfUrl);
        
        // 加载PDF文档
        const loadingTask = pdfjsLib.getDocument(pdfUrl);
        pdfDoc = await loadingTask.promise;
        
        console.log('PDF loaded successfully. Pages:', pdfDoc.numPages);
        
        // 更新页面信息
        document.getElementById('totalPages').textContent = pdfDoc.numPages;
        document.getElementById('fileName').textContent = decodeURIComponent(pdfUrl.split('/').pop());
        
        // 渲染第一页
        renderPage(pageNum);
        
    } catch (error) {
        console.error('Error loading PDF:', error);
        showError('加载PDF失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

// 渲染页面
function renderPage(num) {
    pageRendering = true;
    
    // 使用promise确保页面渲染完成
    pdfDoc.getPage(num).then(function(page) {
        const viewport = page.getViewport({ scale: scale });
        
        // 设置canvas尺寸
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        
        // 渲染PDF页面到canvas
        const renderContext = {
            canvasContext: ctx,
            viewport: viewport
        };
        
        const renderTask = page.render(renderContext);
        
        renderTask.promise.then(function() {
            pageRendering = false;
            
            if (pageNumPending !== null) {
                renderPage(pageNumPending);
                pageNumPending = null;
            }
            
            // 更新页面信息
            document.getElementById('currentPage').textContent = num;
            document.getElementById('zoomLevel').textContent = Math.round(scale * 100) + '%';
            
        }).catch(function(error) {
            console.error('Error rendering page:', error);
            pageRendering = false;
            showError('渲染页面失败: ' + error.message);
        });
    });
}

// 队列渲染页面
function queueRenderPage(num) {
    if (pageRendering) {
        pageNumPending = num;
    } else {
        renderPage(num);
    }
}

// 上一页
function onPrevPage() {
    if (pageNum <= 1) {
        return;
    }
    pageNum--;
    queueRenderPage(pageNum);
}

// 下一页
function onNextPage() {
    if (pageNum >= pdfDoc.numPages) {
        return;
    }
    pageNum++;
    queueRenderPage(pageNum);
}

function zoomIn() {
    if (scale >= 3.0) return;
    scale += 0.25;
    renderPage(pageNum);
}

// 缩小
function zoomOut() {
    if (scale <= 0.5) return;
    scale -= 0.25;
    renderPage(pageNum);
}

// 全屏切换
function toggleFullscreen() {
    const container = document.getElementById('pdf-container');
    
    if (!document.fullscreenElement) {
        container.requestFullscreen().catch(err => {
            console.error('Error attempting to enable fullscreen:', err);
        });
    } else {
        document.exitFullscreen();
    }
}

// 显示/隐藏加载指示器
function showLoading(show) {
    const loading = document.getElementById('loadingIndicator');
    const error = document.getElementById('errorMessage');
    
    if (show) {
        loading.style.display = 'flex';
        error.style.display = 'none';
    } else {
        loading.style.display = 'none';
    }
}

// 显示错误信息
function showError(message) {
    const loading = document.getElementById('loadingIndicator');
    const error = document.getElementById('errorMessage');
    
    loading.style.display = 'none';
    error.style.display = 'flex';
    error.querySelector('p').textContent = message;
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    init();
});
